<template>
  <el-tabs v-model="activeName">
    <el-tab-pane label=" 用户管理
  " name="first">
      <el-row class="user-condition">
        <h3 class="title">筛选</h3>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="openid">
            <el-input style="width: 400px" placeholder="用户的唯一标识openid" v-model="form.openid"></el-input>
          </el-form-item>
          <el-form-item label="是否关注">
            <el-radio-group v-model="form.follow">
              <el-radio value="" label="全部"></el-radio>
              <el-radio value="0" label="未关注"></el-radio>
              <el-radio value="1" label="已关注"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="关注时间">
            <el-col :span="3">
              <el-date-picker type="date" placeholder="选择日期" v-model="dateMin"
                              style="width: 100%;"></el-date-picker>
            </el-col>
            <el-col class="line" :span="0.1">&nbsp;&nbsp;-&nbsp;&nbsp;</el-col>
            <el-col :span="3">
              <el-date-picker type="date" placeholder="选择日期" v-model="dateMax"
                              style="width: 100%;"></el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="分组">
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model="form.TagName"
              :fetch-suggestions="conditionQuerySearch"
              placeholder="请输入内容"
              style="width: 400px"
              @select="conditionSelect">
              <i
                class="el-icon-edit el-input__icon"
                slot="suffix"
                @click="handleIconClick">
              </i>
              <template slot-scope="props">
                <div class="name">{{ props.item.name }}</div>
                <span class="addr">id : {{ props.item.id }}</span>
                <span class="addr" style="margin-left: 20px">人数 : {{ props.item.count }}</span>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="conditionClick()">提交</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row class="user-list">
        <el-table
          ref="multipleTable"
          :data="userData[currentPage]"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection">
          </el-table-column>
          <el-table-column
            label="呢称"
            width="150">
            <template slot-scope="scope">{{ scope.row.nickname }}</template>
          </el-table-column>
          <el-table-column
            label="头像"
            width="100">
            <template slot-scope="scope">
              <img :src="scope.row.headimgurl" width="46" height="46" alt="">
            </template>
          </el-table-column>
          <el-table-column
            label="备注" width="150">
            <template slot-scope="scope">
              {{ scope.row.remark ? scope.row.remark : '无' }}
            </template>
          </el-table-column>
          <el-table-column
            label="是否关注" width="100">
            <template slot-scope="scope">
              {{ scope.row.subscribe == 0 ? '未关注' : '已关注' }}
            </template>
          </el-table-column>
          <el-table-column
            label="关注时间" width="120">
            <template slot-scope="scope">
              {{ new Date(parseInt(scope.row.subscribe_time) * 1000).toLocaleDateString()}}
            </template>
          </el-table-column>
          <el-table-column
            label="性别" width="100">
            <template slot-scope="scope">{{ scope.row.sex == 1 ? '男' : (scope.row.sex == 2 ? '女' : '未知') }}</template>
          </el-table-column>
          <el-table-column
            label="分组" width="200">
            <template slot-scope="scope">
              {{
              scope.row.tagName_list.length > 0 ?
              (scope.row.tagName_list.toString().length > 30 ? scope.row.tagName_list.toString().slice(0, 30) + '...' :
              scope.row.tagName_list.toString())
              : '无'
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="地区" width="150">
            <template slot-scope="scope">{{ scope.row.country + "-" + scope.row.province + "-" + scope.row.city }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作" width="350">
            <template slot-scope="scope">
              <el-button type="primary" @click="synchro([scope.row.openid])" size="mini">同步</el-button>
              <el-button type="primary" @click="model('show',[scope.row.openid],'bind')" size="mini">打标签</el-button>
              <el-button type="info"
                         @click="model('show',[scope.row.openid],'cancel',scope.row.tagid_list,scope.row.tagName_list)"
                         size="mini">取消标签
              </el-button>
              <el-button type="primary" @click="setRemarks(scope.row.openid, scope.row.remark)" size="mini">备注
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="user-btn">
          <el-button type="primary" @click="synchro()" size="small">同步</el-button>
          <el-button type="warning" @click="allSynchro()" size="small">全部同步</el-button>
          <el-button type="success" @click="model('show', [], 'bind')" size="small">批量打标签</el-button>
          <el-button type="info" @click="model('show', [], 'cancel')" size="small">批量打标签</el-button>
        </div>
        <div class="page">
          <el-pagination
            @current-change="handleCurrentChange"
            :page-size="20"
            :current-page="currentPage"
            layout="total, prev, pager, next, jumper"
            :total="TotalNumber">
          </el-pagination>
        </div>
      </el-row>
      <div ref="model" class="model">
        <div ref="bind">
          <div class="title">
            打标签
          </div>
          <div class="content">
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model="TagName"
              :fetch-suggestions="bindquerySearch"
              placeholder="请输入内容"
              style="width: 100%"
              @select="handleSelect">
              <i
                class="el-icon-edit el-input__icon"
                slot="suffix"
                @click="handleIconClick">
              </i>
              <template slot-scope="props">
                <div class="name">{{ props.item.name }}</div>
                <span class="addr">id : {{ props.item.id }}</span>
                <span class="addr" style="margin-left: 20px">人数 : {{ props.item.count }}</span>
              </template>
            </el-autocomplete>
          </div>
          <div class="bottomBtn">
            <el-button @click="model('hide')" size="mini">取消</el-button>
            <el-button @click="bindTag('bind')" type="primary" size="mini">确认</el-button>
          </div>
        </div>
        <div ref="cancel" style="display: none;">
          <div class="title">
            取消标签
          </div>
          <div class="content">
            <el-autocomplete
              popper-class="my-autocomplete"
              v-model="TagName"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              style="width: 100%"
              @select="handleSelect">
              <i
                class="el-icon-edit el-input__icon"
                slot="suffix"
                @click="handleIconClick">
              </i>
              <template slot-scope="props">
                <div class="name">{{ props.item.cancelTagName }}</div>
                <span class="addr">id : {{ props.item.cancelTagid }}</span>
              </template>
            </el-autocomplete>
          </div>
          <div class="bottomBtn">
            <el-button @click="model('hide')" size="mini">取消</el-button>
            <el-button @click="bindTag('cancel')" type="primary" size="mini">确认</el-button>
          </div>
        </div>
      </div>
      <div ref="bgMmodel" @click="model('hide')" class="bg-model"></div>
    </el-tab-pane>
  </el-tabs>
</template>
<script type="text/ecmascript-6">
  export default {
    data() {
      return {
        activeName: 'first',
        userData: {},   // 用户数据
        multipleSelection: [],
        multipleSelectionIndex: [],
        currentPage: 1,   // 当前页数
        TotalNumber: 0, // 总数据条数
        clickPage: [1], // 已经点击过的页面 避免重复请求
        tagListData: [], // 标签列表
        TagName: '', // 绑定或取消 标签name
        Tagid: '', // 绑定或取消 标签id
        openidTag: [], // 绑定或取消 标签 的用户openid
        cancelTagName: [], // 取消标签name 列表
        cancelTagid: [], // 取消标签id 列表
        cancelTagListData: [], // 取消标签列表
        formBool: false, // 判断筛选条件是否变化
        form: { // 筛选条件
          openid: '', // openid 直接搜索 如果有输入openid后面的条件全部忽略
          follow: '全部', // 是否关注
          dateMin: '', // 按时间筛选 最小时间
          dateMax: '', // 按时间筛选 最大时间
          TagId: '', // 分组id
          TagName: '' // 分组名称
        },
        dateMin: '', // 按时间筛选 最小时间
        dateMax: '' // 按时间筛选 最大时间
      }
    },
    mounted() {
      this.userList()
      this.tagList()
    },
    methods: {
      // 获取user列表
      userList(currentPage) {
        const _self = this
        _self.$ajax.post('/weChat/userList', {currentPage: currentPage, form: _self.form}).then(function (response) {
          if (response.data.data.currentPage === 1) {
            _self.TotalNumber = response.data.data.TotalNumber
            _self.userData = {}
            _self.clickPage = [1]
          }
          _self.userData[response.data.data.currentPage] = response.data.data.userData
          _self.currentPage = response.data.data.currentPage
        }).catch(function (error) {
          console.log(error)
        })
      },
      conditionClick() {
        if (this.formBool) {
          const _self = this
          _self.currentPage = 1
          this.formBool = false
          _self.userList(1)
        } else {
          this.$message({
            type: 'info',
            message: '筛选条件未变化！'
          })
        }
      },
      // 当期点击的分页
      handleCurrentChange(val) {
        const _self = this
        if (_self.clickPage.indexOf(val) === -1) {
          this.userList(val)
          _self.clickPage.push(val)
        } else {
          _self.currentPage = val
        }
      },
      // 设置选中
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 选中时触发
      handleSelectionChange(val) {
        this.multipleSelection = []
        this.multipleSelectionIndex = []
        for (let i = 0; val.length > i; i++) {
          this.multipleSelection.push(val[i].openid)
          this.multipleSelectionIndex.push(this.userData[this.currentPage].indexOf(val[i]))
          if (i === 0) {
            this.cancelTagName = val[i].tagName_list
            this.cancelTagid = val[i].tagid_list
          }
          this.cancelTagName = sameElement(this.cancelTagName, val[i].tagName_list)
          this.cancelTagid = sameElement(this.cancelTagid, val[i].tagid_list)
        }

        function sameElement(arr1, arr2) {
          let long = arr1.length < arr2.length ? arr2 : arr1
          let short = arr1.length < arr2.length ? arr1 : arr2
          let str = ',' + long.toString() + ','
          let result = []
          for (let i in short) {
            if (str.indexOf(',' + short[i] + ',') >= 0) {
              result.push(short[i])
            }
          }
          return result
        }
      },
      // 同步
      synchro(ids) {
        const _self = this
        let openids = ids || this.multipleSelection
        _self.$confirm('确认要同步吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _self.$ajax.post('/weChat/WXuserList', {
            openids: openids,
            synchro: 'synchro'
          }).then(function (response) {
            _self.userList(_self.currentPage)
            _self.$message({
              type: 'success',
              message: '同步成功!'
            })
          }).catch(function (error) {
            console.log(error)
          })
        }).catch(() => {
        })
      },
      // 全部同步
      allSynchro() {
        const _self = this
        _self.$confirm('确认要全部同步吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _self.$ajax.post('/weChat/WXuserList', {
            synchro: 'allSynchro'
          }).then(function (response) {
            _self.userList(1)
            _self.$message({
              type: 'success',
              message: '同步成功!'
            })
          }).catch(function (error) {
            console.log(error)
          })
        }).catch(() => {
        })
      },
      // setRemarks 设置备注
      setRemarks(openid, remarks) {
        let _self = this
        this.$prompt('备注(最多30个字符)', '提示', {
          inputValue: remarks,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^.{0,10}$/,
          inputErrorMessage: '最多10个字'
        }).then(({value}) => {
          _self.$ajax.post('/weChat/setRemarks', {
            remarks: value,
            openid: openid
          }).then(function (response) {
            _self.userList(_self.currentPage)
            if (response.data.code === 0) {
              _self.$message({
                type: 'success',
                message: '设置备注成功!'
              })
            } else {
              _self.$message({
                type: 'info',
                message: '设置备注失败'
              })
            }
          }).catch(function (error) {
            console.log(error)
          })
        }).catch(() => {
        })
      },
      // 打标签
      bindTag(state) {
        const _self = this
        let url = ''
        let tagList = []
        if (state === 'bind') {
          url = '/weChat/bindTag'
          tagList = _self.tagListData
        } else {
          url = '/weChat/cancelTag'
          tagList = _self.cancelTagListData
        }
        if (_self.Tagid === '') {
          for (let i = 0; tagList.length > i; i++) {
            if (_self.TagName === tagList[i].cancelTagName) {
              _self.Tagid = tagList[i].cancelTagid
            } else if (i === tagList.length - 1) {
              _self.$message({
                type: 'info',
                message: '未选择标签组！'
              })
              return
            }
          }
        }
        let openids = _self.openidTag.length > 0 ? _self.openidTag : _self.multipleSelection
        _self.$ajax.post(url, {
          openids: openids,
          tagId: _self.Tagid,
          tagName: _self.TagName
        }).then(function (response) {
          if (response.data.code === 0) {
            _self.userList(_self.currentPage)
            _self.$message({
              type: 'success',
              message: response.data.msg
            })
          } else {
            _self.$message({
              type: 'info',
              message: response.data.msg
            })
          }
          _self.TagName = ''
          _self.Tagid = ''
          _self.model('hide')
        }).catch(function (error) {
          console.log(error)
        })
      },
      // 模态框
      model(state, openid, tagsTate, tagidList, tagNameList) {
        const _self = this
        let bgMmodel = _self.$refs.bgMmodel
        let model = _self.$refs.model
        let bind = _self.$refs.bind
        let cancel = _self.$refs.cancel
        if (state === 'show') {
          if (tagsTate === 'bind') {
            bind.style.display = 'block'
            cancel.style.display = 'none'
          } else {
            bind.style.display = 'none'
            cancel.style.display = 'block'
            _self.cancelTagName = tagNameList || _self.cancelTagName
            _self.cancelTagid = tagidList || _self.cancelTagid
            if (_self.cancelTagid.length <= 0) {
              _self.$message({
                type: 'info',
                message: '当前用户没有标签，或者批量取消标签的用户没有相同标签！'
              })
            }
          }
          _self.openidTag = openid
          bgMmodel.style.opacity = 0.5
          bgMmodel.style.visibility = 'inherit'
          model.style.visibility = 'inherit'
          model.style.opacity = 1
          model.style.marginTop = '0'
        } else {
          _self.Tagid = ''
          _self.TagName = ''
          _self.openidTag = []
          bgMmodel.style.opacity = 0
          bgMmodel.style.visibility = 'hidden'
          model.style.visibility = 'hidden'
          model.style.opacity = 0
          model.style.marginTop = '-20px'
        }
      },
      // 获取标签列表
      tagList() {
        let _self = this
        _self.$ajax.post('/weChat/tagList').then(function (response) {
          if (response.data.code === 0) {
            _self.tagListData = response.data.data
          } else {
            _self.$message({
              type: 'info',
              message: '获取标签失败！'
            })
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      // element ui 模态框
      // 打标签
      bindquerySearch(queryString, cb) {
        var restaurants = this.tagListData
        var results = queryString ? restaurants.filter(this.createFilter(queryString, 'name')) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      // 取消标签
      querySearch(queryString, cb) {
        const _self = this
        var restaurants = []
        for (let i = 0; i < _self.cancelTagName.length; i++) {
          restaurants.push({
            cancelTagName: _self.cancelTagName[i],
            cancelTagid: _self.cancelTagid[i]
          })
        }
        _self.cancelTagListData = restaurants
        var results = queryString ? restaurants.filter(this.createFilter(queryString, 'cancelTagName')) : restaurants
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
      createFilter(queryString, key) {
        return (restaurant) => {
          return (restaurant[key].toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      // 用户分组选择
      handleSelect(item) {
        this.TagName = item.name || item.cancelTagName
        this.Tagid = item.id || item.cancelTagid
      },
      handleIconClick(ev) {
        console.log(ev)
      },
      // 用户筛选 分组条件
      conditionQuerySearch(queryString, cb) {
        var restaurants = this.tagListData
        var results = queryString ? restaurants.filter(this.conditionCreateFilter(queryString, 'name')) : restaurants
        // 调用 callback 返回建议列表的数据
        if (queryString === '') {
          this.form.TagId = ''
        }
        cb(results)
      },
      conditionCreateFilter(queryString, key) {
        return (restaurant) => {
          if (queryString === restaurant[key]) {
            this.form.TagId = restaurant.id
          }
          return (restaurant[key].toLowerCase().indexOf(queryString.toLowerCase()) === 0)
        }
      },
      conditionSelect(item) {
        this.form.TagName = item.name || item.cancelTagName
        this.form.TagId = item.id || item.cancelTagid
      }
      // element ui 模态框
    },
    watch: {
      form: {
        handler(curVal, oldVal) {
          this.formBool = true
        },
        deep: true
      },
      'dateMin'(curVal, oldVal) {
        if (this.dateMin === null) {
          this.form.dateMin = ''
          this.dateMin = ''
          return
        } else if (this.dateMin !== '') {
          this.form.dateMin = +curVal
        }
        if (this.form.dateMin !== '') {
          if ((+curVal) >= this.form.dateMax && this.form.dateMax !== '') {
            this.form.dateMin = ''
            this.dateMin = ''
            this.$message({
              type: 'info',
              message: '不能超过最大时间！'
            })
          }
        }
      },
      'dateMax'(curVal, oldVal) {
        if (this.dateMax === null) {
          this.form.dateMax = ''
          this.dateMax = ''
          return
        } else if (this.dateMax !== '') {
          this.form.dateMax = +curVal
        }
        // console.info(this.form.dateMax)
        if (this.form.dateMax !== '') {
          if ((+curVal) <= this.form.dateMin && this.form.dateMin !== '') {
            this.form.dateMax = ''
            this.dateMax = ''
            this.$message({
              type: 'info',
              message: '不能小于最小时间！'
            })
          }
        }
      }
    }
  }
</script>
<style lang='less' scoped>
  @import 'user.less';

  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px;

      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }

      .highlighted .addr {
        color: #ddd;
      }
    }
  }
</style>
